# -*- coding: UTF-8 -*-

import socket
import time
import struct
import json
import random
import msgpack

#创建套接字
tcpClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('socket---%s'%tcpClientSocket)
#链接服务器
serverAddr = ('127.0.0.1',8888)
tcpClientSocket.connect(serverAddr)
print('connect success!')


def bytes_to_int(str, byteorder, signed = False):
    return int.from_bytes(str, byteorder=byteorder, signed=signed)

def send(c, m, data):
    #发送数据
    a = bytearray()
    cmd = {
        'c':c,
        'm': m,
        'data': data
    }
    s = msgpack.packb(cmd, use_bin_type=True)
    l = len(s)
    x = struct.pack('>H', l)
    a.extend(bytearray(x))
    a.extend(s)
    sendData = bytes(a)
    if len(sendData) > 0:
        tcpClientSocket.send(sendData)




id = random.randint(10000, 100000)
send("game", 'login', {'id': str(id), 'roomid': "123456", "subid":1, "token":"qwe123"})

while True:
    head = tcpClientSocket.recv(2)
    datalen = head[0:2]
    l = bytes_to_int(datalen, 'big')
    data = tcpClientSocket.recv(l)
    resp = msgpack.unpackb(data)
    print('resp->', resp)
    #打印接收到的数据
    pass
#关闭套接字
tcpClientSocket.close()
print('close socket!')
